package com.compus_help.service.impl;

import com.compus_help.Mapper.AdminMapper;
import com.compus_help.common.Constants;
import com.compus_help.common.JwtUtil;
import com.compus_help.common.PageResult;
import com.compus_help.common.defaultdate;
import com.compus_help.controller.admin.adminOrderController;
import com.compus_help.entity.DTO.*;
import com.compus_help.entity.Pojo.Admin;
import com.compus_help.entity.Pojo.Student;
import com.compus_help.entity.VO.AdminLoginVO;
import com.compus_help.interceptor.JwtInterceptor;
import com.compus_help.service.AdminService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    private static final Logger log = LoggerFactory.getLogger(adminOrderController.class);
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private JwtInterceptor jwtInterceptor;
    @Autowired
    private HttpServletRequest request;

    //

    /**
     *管理员登录
     * @param adminLogindto
     * @return
     */
    @Override
    public AdminLoginVO adminLogin(AdminLoginDTO adminLogindto) {
        // 从数据库查询管理员信息
        Admin admin = adminMapper.adminLogin(adminLogindto);


        // 检查是否查询到用户
        if (admin == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 组装claims
        Map<String, Object> claims = new HashMap<>();
        claims.put("adminId", admin.getAdminId());
        claims.put("adminname", admin.getAdminName());

        // 添加空值检查
        if (admin.getAdminId() == null) {
            throw new RuntimeException("管理员ID为空，无法生成token");
        }

        // 调用生成token方法
        String token = jwtUtil.generateToken(claims, admin.getAdminId().toString());

        // 封装返回结果
        return AdminLoginVO.builder(admin, token);
    }

    /**
     *添加学生
     * @param studentDTO
     */
    @Override
    public void addStudent(studentDTO studentDTO) {
        //创建stdent 对象将studentDTO对象中的数据复制到student对象中
        Student student = new Student();
        BeanUtils.copyProperties(studentDTO, student);
        log.info("添加学生：{}", student);
        //更新数据
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        student.setCancelCount(defaultdate.DEFAULT_CANCEL_COUNT);
        student.setCanAcceptOrder(defaultdate.DEFAULT_CAN_ACCEPT_ORDER);
        student.setCanPublishOrder(defaultdate.DEFAULT_CAN_PUBLISH_ORDER);

        // 插入数据库
        adminMapper.addStudent(student);
    }
    //

    /**
     *删除学生
     * @param studentIds
     */
    @Override
    public void deleteStudents(List<String> studentIds) {
        //判断是否有未完成的订单

        //删除
        //TODO
    }

    /**
     * 学生分页查询
     * @param studentPageDTO
     * @return
     */
    @Override
    public PageResult getStudents(studentPageDTO studentPageDTO) {
        //设置分页参数
        PageHelper.startPage(studentPageDTO.getPage(),studentPageDTO.getPageSize());
        Page<Student> page = adminMapper.pageQuery(studentPageDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 修改学生接单权限
     * @param studentId
     */
    @Override
    public void updateAcceptOrder(String studentId) {
        adminMapper.updateAcceptOrder(studentId);
        log.info("修改学生接单权限：{}", studentId);
    }

    /**
     * 修改学生发布订单权限
     * @param studentId
     */
    @Override
    public void updatePublicOrder(String studentId) {
        adminMapper.updatePublicOrder(studentId);
        log.info("修改学生发布订单权限：{}", studentId);
    }

    /**
     * 修改学生信息
     * @param studentDTO
     */
    @Override
    public void updateStudentInfo(studentDTO studentDTO) {
        // 从当前线程中获取请求属性（需要配合RequestContextHolder使用）
        // 或者通过其他方式获取当前操作管理员信息
        if (request != null) {
            Long adminId = (Long) request.getAttribute(Constants.USER_ID_ATTRIBUTE);
            if (adminId != null) {
                studentDTO.setUpdateUser(adminId.toString());
            }
        }
        // 更新时间
        studentDTO.setUpdateTime(LocalDateTime.now());
        adminMapper.updateStudentInfo(studentDTO);
    }
}
